package com.guodi.model.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.minio.util.MinioUtil;
import com.guodi.core.secure.utils.AuthUtil;
import com.guodi.core.tool.api.R;
import com.guodi.core.tool.utils.StringUtil;
import com.guodi.map.feign.IMapClient;
import com.guodi.model.constant.IdtIndicatorsConst;
import com.guodi.model.entity.*;
import com.guodi.model.enums.IdtFillTaskMessageTypeEnum;
import com.guodi.model.enums.IdtFillTaskStatusEnum;
import com.guodi.model.mapper.IdtFillTaskMapper;
import com.guodi.model.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guodi.model.utils.RegularUtils;
import com.guodi.model.vo.ApiIndicatorsDirFillTaskVo;
import com.guodi.model.vo.ApiIndicatorsFillTaskVo;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.pl.REGON;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 指标填报任务表 服务实现类
 *
 * @author lzy
 * @date 2023-05-08
 */
@Service
public class IdtFillTaskServiceImpl extends ServiceImpl<IdtFillTaskMapper, IdtFillTask> implements IIdtFillTaskService {

    @Resource
    private IdtFillTaskMapper idtFillTaskMapper;
    @Resource
    private IIdtIndicatorsTypeService iIdtIndicatorsTypeService;
    @Resource
    private IIdtIndicatorsService idtIndicatorsService;
    @Resource
    private IIdtIndicatorsDirService iIdtIndicatorsDirService;
    @Resource
    private IIdtWarnRuleService iIdtWarnRuleService;
    @Resource
    private IIdtFillValueService iIdtFillValueService;
    @Resource
    private IIdtFillTaskMessageService iIdtFillTaskMessageService;
    @Resource
    private IIdtMonitorValueService iIdtMonitorValueService;
    @Resource
    @Lazy
    private IIdtFillProblemService iIdtFillProblemService;
    @Resource
    @Lazy
    private IIdtFillTaskOpinionService iIdtFillTaskOpinionService;
    @Resource
    private IIdtFillTaskScoreService iIdtFillTaskScoreService;

    @Resource
    private IMapClient iMapClient;
    @Resource
    private IRedisDictService iRedisDictService;

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static String MONITOR_WARNING_CODE = "monitor-warning";


    @Override
    public void iSSueTask(String year, List<String> divisions, String endTime) {

        Map<String, String> divisionMap = iMapClient.mapDivisionCode2Name(divisions.toArray(new String[divisions.size()]));

        List<IdtFillTask> list = new ArrayList<>();
        for (String division : divisions) {
            IdtFillTask entity = new IdtFillTask();
            prepareData(entity, true);
            entity.setDivisionCode(division);
            entity.setDivisionName(divisionMap.get(division));
            entity.setYear(year);
            entity.setStatus(IdtFillTaskStatusEnum.WAIT_FILLED.getCode());
            entity.setIssueTime(sdf.format(new Date()));
            entity.setName(year + "年" + entity.getDivisionName());
            entity.setEndTime(endTime);
            list.add(entity);
        }
        this.saveBatch(list);
    }

    @Override
    public List listCountByCityLevel(String year) {
        String regionCode = AuthUtil.getUserRegionCode();
        List<Map<String, Object>> resultList = new ArrayList();
        if (regionCode.length() == 2) {
            //省级用户，需要查询市级、区县级
            List<IdtFillTask> cityList = idtFillTaskMapper.listByCondition(year, regionCode, 4);
            Map<String, Object> map1 = new LinkedHashMap<>();
            map1.put("type", "市级");
            map1.put("data", groupByStatus(cityList));
            resultList.add(map1);

            List<IdtFillTask> countyList = idtFillTaskMapper.listByCondition(year, regionCode, 6);
            Map<String, Object> map2 = new LinkedHashMap<>();
            map2.put("type", "区县");
            map2.put("data", groupByStatus(countyList));
            resultList.add(map2);
        } else if (regionCode.length() == 4) {
            List<IdtFillTask> countyList = idtFillTaskMapper.listByCondition(year, regionCode, 6);
            Map<String, Object> map1 = new LinkedHashMap<>();
            map1.put("type", "区县");
            map1.put("data", groupByStatus(countyList));
            resultList.add(map1);

            List<IdtFillTask> streetList = idtFillTaskMapper.listByCondition(year, regionCode, 9);
            Map<String, Object> map2 = new LinkedHashMap<>();
            map2.put("type", "街镇");
            map2.put("data", groupByStatus(streetList));
            resultList.add(map2);
        }
        return resultList;
    }

    @Override
    public IPage<ApiIdtFillTask> listByCondition(Page page, String year, int codeLength) {
        String regionCode = AuthUtil.getUserRegionCode();
        IPage<ApiIdtFillTask> iPage = idtFillTaskMapper.pageByCondition(page, year, regionCode, codeLength);
        if (CollectionUtils.isNotEmpty(iPage.getRecords())) {

            Map<String, String> divisionMap = iMapClient.mapAllDivision();

            for (ApiIdtFillTask task : iPage.getRecords()) {
                task.setStatus(IdtFillTaskStatusEnum.getNameByCode(task.getStatus()));
                //市区街道翻译
                this.assignmentDivisionName(task, divisionMap);
            }
        }

        return iPage;
    }

    /**
     * @描述: 市区街道翻译
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/22 16:08
     **/
    private void assignmentDivisionName(ApiIdtFillTask apiIdtFillTask, Map<String, String> divisionMap) {
        int length = apiIdtFillTask.getDivisionCode().length();
        String city = "";
        String county = "";
        String street = "";
        if (length == 4) {
            //市
            city = divisionMap.get(apiIdtFillTask.getDivisionCode());
        } else if (length == 6) {
            //区
            city = divisionMap.get(apiIdtFillTask.getDivisionCode().substring(0, 4));
            county = divisionMap.get(apiIdtFillTask.getDivisionCode());
        } else if (length == 9) {
            //街道
            city = divisionMap.get(apiIdtFillTask.getDivisionCode().substring(0, 4));
            county = divisionMap.get(apiIdtFillTask.getDivisionCode().substring(0, 6));
            street = divisionMap.get(apiIdtFillTask.getDivisionCode());
        }
        apiIdtFillTask.setCity(city);
        apiIdtFillTask.setCounty(county);
        apiIdtFillTask.setStreet(street);
    }

    /**
     * @描述: 获取行政区级别的分状态列表数据
     * @入参:list 列表数据
     * @入参:type 0：统计待确认、1：不统计待确认
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/16 15:23
     **/
    private Map<String, Integer> groupByStatus(List<IdtFillTask> list) {

        Map<String, Integer> map = new LinkedHashMap<>();

        Map<String, List<IdtFillTask>> statusListMap = list.stream().collect(Collectors.groupingBy(IdtFillTask::getStatus));

        for (IdtFillTaskStatusEnum value : IdtFillTaskStatusEnum.values()) {
            String code = value.getCode();
            List<IdtFillTask> idtFillTasks = statusListMap.getOrDefault(code, new ArrayList<>());

            map.put(value.getName(), idtFillTasks.size());
        }

        return map;
    }

    /**
     * @描述: 校验任务是否满足提交条件
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/16 17:29
     **/
    public boolean verifySubmit(IdtFillTask task) {
        boolean flag = true;
        if (!Objects.equals(IdtFillTaskStatusEnum.WAIT_FILLED.getCode(), task.getStatus())) {
            flag = false;
            return flag;
        }
        //该任务填报值
        Map<String, IdtFillValue> indicatorsId2ValueMap = iIdtFillValueService.indicatorsId2ValueMap(task.getId());
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(MONITOR_WARNING_CODE, task.getYear(), task.getDivisionCode());
        List<ApiIndicatorsDirFillTaskVo> treeList = idtFillTaskMapper.listDirByCode(one.getId(), null);
        for (ApiIndicatorsDirFillTaskVo dir : treeList) {
            if (dir.getType() == 2) {
                //填报值
                IdtFillValue fillValue = indicatorsId2ValueMap.get(dir.getIndicatorsId());
                if (fillValue == null) {
                    flag = false;
                    break;
                }
            }
        }
        return flag;
    }

    @Override
    public IPage<IdtFillTask> estimateList(Page page, String year, String regionCode) {
        LambdaQueryWrapper<IdtFillTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IdtFillTask::getDivisionCode, regionCode);
        //dhj去年年份筛选
        //wrapper.eq(IdtFillTask::getYear,year);
        wrapper.eq(IdtFillTask::getStatus, IdtFillTaskStatusEnum.WAIT_ESTIMATE.getCode());
        wrapper.orderByDesc(IdtFillTask::getCreateTime);
        IPage<IdtFillTask> iPage = this.page(page, wrapper);
        if (CollectionUtils.isNotEmpty(iPage.getRecords())) {
            for (IdtFillTask task : iPage.getRecords()) {
                task.setName(task.getName() + IdtFillTaskStatusEnum.getStatusByCode(task.getStatus()));
            }
        }
        return iPage;
    }

    @Override
    public IPage<IdtFillTask> completedList(Page page, String year, String regionCode) {
        LambdaQueryWrapper<IdtFillTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IdtFillTask::getDivisionCode, regionCode);
        //dhj去掉年份筛选
        //wrapper.eq(IdtFillTask::getYear,year);
        wrapper.eq(IdtFillTask::getStatus, IdtFillTaskStatusEnum.COMPLETED.getCode());
        wrapper.orderByDesc(IdtFillTask::getCreateTime);
        IPage<IdtFillTask> iPage = this.page(page, wrapper);
        if (CollectionUtils.isNotEmpty(iPage.getRecords())) {
            for (IdtFillTask task : iPage.getRecords()) {
                task.setName(task.getName() + IdtFillTaskStatusEnum.getStatusByCode(task.getStatus()));
            }
        }
        return iPage;
    }

    @Override
    public boolean editStatus(String taskId, String status) {
        LambdaUpdateWrapper<IdtFillTask> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(IdtFillTask::getStatus, status);
        wrapper.set(IdtFillTask::getModifier, AuthUtil.getUserId().toString());
        wrapper.set(IdtFillTask::getModifyTime, new Date());
        wrapper.eq(IdtFillTask::getId, taskId);
        boolean update = this.update(wrapper);
        return update;
    }

    @Override
    public R downloadReportFile(String taskId, HttpServletResponse response) {
        IdtFillTask task = this.getById(taskId);
        if (task == null) {
            return R.fail("暂无报告，下载失败");
        }
        CmeReport report = this.idtFillTaskMapper.getReportByYearAndDivision(task.getYear(), task.getDivisionCode());
        if (report == null) {
            return R.fail("暂无报告，下载失败");
        }
        InputStream inputStream = MinioUtil.download(report.getWordFilePath());
        ServletOutputStream outputStream = null;
        try {
            String reportName = report.getWordFilePath().substring(report.getWordFilePath().lastIndexOf("/") + 1);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(reportName, "UTF-8"));
            outputStream = response.getOutputStream();
            int len = 0;
            byte[] buf = new byte[10240];
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
            R.success("下载成功");
        } catch (IOException e) {
            e.printStackTrace();
            R.fail("下载失败");
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return R.success("下载成功");

    }

    @Override
    public Map<String, List<ApiIndicatorsFillTaskVo>> getIndicatorsDirByTaskId(String taskId) {
        // 用于存放《指标维度，指标列表》
        Map<String, List<ApiIndicatorsFillTaskVo>> dirNameToListMap = new LinkedHashMap<>();

        IdtFillTask task = this.getById(taskId);
        if (task == null) {
            return dirNameToListMap;
        }
        //获取根据编码获取体系类型
        IdtIndicatorsType one = iIdtIndicatorsTypeService.findByCode(MONITOR_WARNING_CODE, task.getYear(), task.getDivisionCode());
        List<ApiIndicatorsDirFillTaskVo> treeList = idtFillTaskMapper.listDirByCode(one.getId(), null);

        //指标类型map
        Map<String, String> typeMap = iRedisDictService.getItemMaps(IdtIndicatorsConst.DICT_INDICATORS_TYPE);
        // 获取所有子单位，基础运维未提供
        Map<String, String> deptMap = idtIndicatorsService.getDeptNameMap();
        // 获取指标预警规则
        Map<String, String> warnRuleMap = iIdtWarnRuleService.getWarnRuleMapById();
        //<指标编码，指标>
        Map<String, IdtIndicators> idtIndicatorsMap = iIdtIndicatorsDirService.mapCode2IdtIndicators();
        //该任务填报值
        Map<String, IdtFillValue> indicatorsId2ValueMap = iIdtFillValueService.indicatorsId2ValueMap(taskId);

        //提取各个维度
        List<ApiIndicatorsDirFillTaskVo> parentDir = treeList.stream().filter(d -> d.getType() == 1 && d.getTreeLevel() == 0).collect(Collectors.toList());

        for (ApiIndicatorsDirFillTaskVo pDir : parentDir) {
            //用于存放指标集
            List<ApiIndicatorsFillTaskVo> list = new ArrayList<>();
            this.listByParentId(pDir.getId(), treeList, list);
            dirNameToListMap.put(pDir.getName(), list);

            for (ApiIndicatorsFillTaskVo dir : list) {
                //指标类型
                if (StringUtils.isNotBlank(dir.getIdtType())) {
                    dir.setIdtType(typeMap.get(dir.getIdtType()));
                }
                //处理责任单位多级中文名问题
                String dutyCodes = dir.getIdtDutyCompany();
                if (org.apache.commons.lang.StringUtils.isNotBlank(dutyCodes)) {
                    dir.setIdtDutyCompany(idtIndicatorsService.getDeptNameStr(dutyCodes, deptMap));
                }

                //处理责任处室多级中文名问题
                String codes = dir.getIdtDutyDepartment();
                if (org.apache.commons.lang.StringUtils.isNotBlank(codes)) {
                    dir.setIdtDutyDepartment(idtIndicatorsService.getDeptNameStr(codes, deptMap));
                }
                //处理规则说明
                if (StringUtils.isNotBlank(dir.getIdtWarnRuleId())) {
                    dir.setIdtWarnRuleId(warnRuleMap.get(dir.getIdtWarnRuleId()));
                }
                //填报值
                IdtFillValue fillValue = indicatorsId2ValueMap.getOrDefault(dir.getIndicatorsId(), null);
                if (fillValue != null) {
                    dir.setFillValue(fillValue);
                }
                //用户自定义指标编码
                if (StringUtils.isBlank(dir.getIndicatorsCustomCode())) {
                    dir.setIndicatorsCustomCode(dir.getIdtCode());
                }
                //处理指标因子
                if (dir.getIdtDatasource().equals("formula") && StringUtils.isNotBlank(dir.getCalculateResult())) {
                    List<String> idtCodes = RegularUtils.extractString(dir.getCalculateResult());
                    List<ApiIndicatorsFillTaskVo> calculateList = new ArrayList<>();
                    for (String code : idtCodes) {
                        IdtIndicators idtIndicators = idtIndicatorsMap.get(code);
                        if (idtIndicators != null) {
                            ApiIndicatorsFillTaskVo entity = new ApiIndicatorsFillTaskVo();
                            entity.setIndicatorsId(idtIndicators.getId());
                            entity.setIdtCode(idtIndicators.getCode());
                            entity.setIdtName(idtIndicators.getName());
                            entity.setIdtAttribute(idtIndicators.getAttribute());
                            entity.setCalculateFormula(idtIndicators.getCalculateFormula());
                            entity.setCalculateResult(idtIndicators.getCalculateResult());
                            entity.setEstimateRuleConfig(idtIndicators.getEstimateRuleConfig());
                            entity.setWarnRuleConfig(idtIndicators.getWarnRuleConfig());
                            entity.setIdtBaseData(idtIndicators.getBaseData());
                            entity.setIdtBaseDataSource(idtIndicators.getBaseDataSource());
                            entity.setIdtConnotation(idtIndicators.getConnotation());
                            entity.setIdtDatasource(idtIndicators.getDatasource());
                            entity.setIdtUnit(idtIndicators.getUnit());
                            entity.setSort(idtIndicators.getSort());
                            entity.setIdtScope(idtIndicators.getScope());
                            //填报值
                            IdtFillValue value = indicatorsId2ValueMap.getOrDefault(idtIndicators.getId(), null);
                            if (value != null) {
                                entity.setFillValue(value);
                            }
                            //指标类型
                            if (StringUtils.isNotBlank(idtIndicators.getType())) {
                                entity.setIdtType(typeMap.get(idtIndicators.getType()));
                            }
                            //处理责任单位多级中文名问题
                            String cdutyCodes = idtIndicators.getDutyCompany();
                            if (org.apache.commons.lang.StringUtils.isNotBlank(cdutyCodes)) {
                                entity.setIdtDutyCompany(idtIndicatorsService.getDeptNameStr(cdutyCodes, deptMap));
                            }

                            //处理责任处室多级中文名问题
                            String ccodes = idtIndicators.getDutyDepartment();
                            if (org.apache.commons.lang.StringUtils.isNotBlank(ccodes)) {
                                entity.setIdtDutyDepartment(idtIndicatorsService.getDeptNameStr(ccodes, deptMap));
                            }
                            //处理规则说明
                            if (StringUtils.isNotBlank(idtIndicators.getWarnRuleId())) {
                                entity.setIdtWarnRuleId(warnRuleMap.get(idtIndicators.getWarnRuleId()));
                            }
                            calculateList.add(entity);
                        }
                    }
                    dir.setCalculateList(calculateList);
                }
            }

        }


        return dirNameToListMap;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R confirmByTaskId(String taskId) {
        IdtFillTask task = this.getById(taskId);
        if (task == null) {
            return R.fail("找不到任务");
        }
        if (!Objects.equals(IdtFillTaskStatusEnum.WAIT_CONFIRM.getCode(), task.getStatus())) {
            return R.fail("当前任务不处于" + IdtFillTaskStatusEnum.WAIT_CONFIRM.getName() + "状态，请检查");
        }
//        String regionCode = AuthUtil.getUserRegionCode();
//        if(!Objects.equals(regionCode,task.getCreatorDivisionCode())){
//            return R.fail("当前用户无权确认该任务");
//        }
        //修改状态
        task.setStatus(IdtFillTaskStatusEnum.WAIT_ESTIMATE.getCode());
        prepareData(task, false);
        this.updateById(task);

        //更新至正式表
        LambdaQueryWrapper<IdtFillValue> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IdtFillValue::getTaskId, task.getId());
        List<IdtFillValue> values = this.iIdtFillValueService.list(wrapper);
        this.iIdtMonitorValueService.updateDataByFillTask(task.getDivisionCode(), task.getYear(), values);

        //问题触发
        iIdtFillProblemService.generateProblem(task);

        //待评估状态即触发评分计算
        iIdtFillTaskScoreService.deleteByYearAndCode(task.getYear(), task.getDivisionCode());
        iIdtFillTaskScoreService.calcScoreByYearAndCode(null, task.getYear(), task.getDivisionCode());
        return R.data("已完成确认！");
    }

    @Override
    public R rejectByTaskId(String taskId, String message) {
        IdtFillTask task = this.getById(taskId);
        if (task == null) {
            return R.fail("找不到任务");
        }
        if (!Objects.equals(IdtFillTaskStatusEnum.WAIT_CONFIRM.getCode(), task.getStatus())) {
            return R.fail("当前任务不处于" + IdtFillTaskStatusEnum.WAIT_CONFIRM.getName() + "状态，请检查");
        }
//        String regionCode = AuthUtil.getUserRegionCode();
//        if(!Objects.equals(regionCode,task.getCreatorDivisionCode())){
//            return R.fail("当前用户无权退回该任务");
//        }
        //修改状态
        task.setStatus(IdtFillTaskStatusEnum.WAIT_FILLED.getCode());
        prepareData(task, false);
        this.updateById(task);
        //推送消息
        iIdtFillTaskMessageService.saveMessage(taskId, IdtFillTaskMessageTypeEnum.REJECT.getCode(), message);
        return R.data("驳回成功！");
    }

    @Override
    public R urgingByTaskId(String taskId) {
        IdtFillTask task = this.getById(taskId);
        if (task == null) {
            return R.fail("找不到任务");
        }
        if (!Objects.equals(IdtFillTaskStatusEnum.WAIT_FILLED.getCode(), task.getStatus())) {
            return R.fail("当前任务不处于" + IdtFillTaskStatusEnum.WAIT_FILLED.getName() + "状态，请检查");
        }
        String regionCode = AuthUtil.getUserRegionCode();
        if (!Objects.equals(regionCode, task.getCreatorDivisionCode())) {
            return R.fail("当前用户无权催办该任务");
        }
        //推送消息
        iIdtFillTaskMessageService.saveMessage(taskId, IdtFillTaskMessageTypeEnum.URGING.getCode(), null);
        return R.data("已催办！");
    }

    @Override
    public R submitByTaskId(String taskId) {
        IdtFillTask task = this.getById(taskId);
        if (task == null) {
            return R.fail("找不到任务");
        }
        if (!Objects.equals(IdtFillTaskStatusEnum.WAIT_FILLED.getCode(), task.getStatus())) {
            return R.fail("当前任务不处于" + IdtFillTaskStatusEnum.WAIT_FILLED.getName() + "状态，无法提交任务");
        }
        String regionCode = AuthUtil.getUserRegionCode();
        if (!Objects.equals(regionCode, task.getDivisionCode())) {
            return R.fail("当前用户无权提交该任务");
        }
        task.setStatus(IdtFillTaskStatusEnum.WAIT_CONFIRM.getCode());
        prepareData(task, false);
        this.updateById(task);
        //处理消息
        this.iIdtFillTaskMessageService.processedTask(taskId);
        return R.data("已提交！");
    }

    @Override
    public IPage<IdtFillTask> auditTask(Page page, String year) {
        String regionCode = AuthUtil.getUserRegionCode();
        List<String> status = new ArrayList<>();
        status.add(IdtFillTaskStatusEnum.WAIT_CONFIRM.getCode());
        IPage<IdtFillTask> iPage = this.idtFillTaskMapper.taskToExamineList(page, year, regionCode, status);
        if (CollectionUtils.isNotEmpty(iPage.getRecords())) {
            for (IdtFillTask task : iPage.getRecords()) {
                task.setName(task.getName() + IdtFillTaskStatusEnum.getStatusByCode(task.getStatus()));
            }
        }
        return iPage;
    }

    @Override
    public IPage<IdtFillTask> CheckedTask(Page page, String year) {
        String regionCode = AuthUtil.getUserRegionCode();
        List<String> status = new ArrayList<>();
        status.add(IdtFillTaskStatusEnum.WAIT_ESTIMATE.getCode());
        status.add(IdtFillTaskStatusEnum.COMPLETED.getCode());
        IPage<IdtFillTask> iPage = this.idtFillTaskMapper.taskToExamineList(page, year, regionCode, status);
        if (CollectionUtils.isNotEmpty(iPage.getRecords())) {
            for (IdtFillTask task : iPage.getRecords()) {
                task.setName(task.getName() + IdtFillTaskStatusEnum.getStatusByCode(task.getStatus()));
            }
        }
        return iPage;
    }

    @Override
    public R waitFilledList(String year, String regionCode) {
        LambdaUpdateWrapper<IdtFillTask> wrapper = new LambdaUpdateWrapper<>();
        if (StringUtil.isNotBlank(year)) {
            wrapper.eq(IdtFillTask::getYear, year);
        }
        if (StringUtil.isNotBlank(regionCode)) {
            wrapper.eq(IdtFillTask::getDivisionCode, regionCode);
        }
        wrapper.eq(IdtFillTask::getStatus, IdtFillTaskStatusEnum.WAIT_FILLED.getCode());
        List<IdtFillTask> list = this.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return R.data("暂无" + IdtFillTaskStatusEnum.WAIT_FILLED.getStatus() + "数据");
        }
        IdtFillTask task = list.get(0);
        Map<String, List<ApiIndicatorsFillTaskVo>> indicatorsDirByTaskId = this.getIndicatorsDirByTaskId(task.getId());
        task.setIndicatorsDir(indicatorsDirByTaskId);
        return R.data(task);
    }

    @Override
    public R waitConfirmList(String year, String regionCode) {
        LambdaUpdateWrapper<IdtFillTask> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(IdtFillTask::getYear, year);
        wrapper.eq(IdtFillTask::getDivisionCode, regionCode);
        wrapper.eq(IdtFillTask::getStatus, IdtFillTaskStatusEnum.WAIT_CONFIRM.getCode());
        List<IdtFillTask> list = this.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return R.data("暂无" + IdtFillTaskStatusEnum.WAIT_CONFIRM.getStatus() + "数据");
        }
        IdtFillTask task = list.get(0);
        Map<String, List<ApiIndicatorsFillTaskVo>> indicatorsDirByTaskId = this.getIndicatorsDirByTaskId(task.getId());
        task.setIndicatorsDir(indicatorsDirByTaskId);
        return R.data(task);
    }

    private void prepareData(IdtFillTask entity, boolean isSave) {
        if (isSave) {
            entity.setId(UuidUtil.get32UUID());
            entity.setCreator(String.valueOf(AuthUtil.getUserId()));
            entity.setCreatorDivisionCode(AuthUtil.getUserRegionCode());
            entity.setCreateTime(new Date());
            //防止误修改
            entity.setModifier(null);
            entity.setModifyTime(null);
        } else {
            entity.setModifier(String.valueOf(AuthUtil.getUserId()));
            entity.setModifyTime(new Date());
            //防止误修改
            entity.setCreator(null);
            entity.setCreateTime(null);
        }
    }

    /**
     * @描述: 根据id查找所有下级指标
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/5/9 14:50
     **/
    private void listByParentId(String pId, List<ApiIndicatorsDirFillTaskVo> treeList, List<ApiIndicatorsFillTaskVo> list) {
        for (ApiIndicatorsDirFillTaskVo dir : treeList) {
            if (dir.getParentId().equals(pId)) {
                if (dir.getType() == 2) {
                    ApiIndicatorsFillTaskVo indicatorsFillTaskVo = new ApiIndicatorsFillTaskVo();
                    BeanUtils.copyProperties(dir, indicatorsFillTaskVo);
                    list.add(indicatorsFillTaskVo);
                } else {
                    listByParentId(dir.getId(), treeList, list);
                }
            }
        }
    }

    @Override
    public List<IdtFillTaskOpinion> getOptionsByTask(String year, String divisionCode) {
        LambdaQueryWrapper<IdtFillTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IdtFillTask::getYear, year);
        wrapper.eq(IdtFillTask::getDivisionCode, divisionCode);
        IdtFillTask task = this.getOne(wrapper);
        if (null == task) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<IdtFillTaskOpinion> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(IdtFillTaskOpinion::getTaskId, task.getId());
        wrapper1.orderByAsc(IdtFillTaskOpinion::getNum);
        List<IdtFillTaskOpinion> list = this.iIdtFillTaskOpinionService.list(wrapper1);
        return list;
    }

    @Override
    public IdtFillTask getTaskByYearAndCode(String year, String divisionCode) {
        LambdaQueryWrapper<IdtFillTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(IdtFillTask::getYear, year);
        wrapper.eq(IdtFillTask::getDivisionCode, divisionCode);
        wrapper.in(IdtFillTask::getStatus, Arrays.asList(IdtFillTaskStatusEnum.WAIT_ESTIMATE.getCode(), IdtFillTaskStatusEnum.COMPLETED.getCode()));
        List<IdtFillTask> list = this.list(wrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            return list.get(0);
        } else {
            return null;
        }
    }
}
